import storage from "good-storage"

// 搜索记录
const SEARCH_KEY = '_search_'
const SEARCH_MAX_LENGTH = 15
// 播放记录
const PLAY_KEY = '_play_'
const PLAY_MAX_LENGTH = 30
// 收藏的记录
const FAVORITE_KEY = "_favorite_"
const FAVORITE_MAX_LENGTH = 200
// 思路：数组最大存15条数据，每次插入的都放在数组的最前面，
//当大于15条的时候，就把最早的数据删除掉

// 插入数据的公共函数
function insertArray(arr,val,compare,maxlen){
    const index = arr.findIndex(compare)
    // if(index < 0){
    //     return
    // }
    if(index >= 0){
        arr.splice(index,1)
    }
    arr.unshift(val);
    if(maxlen && arr.length >maxlen){
        arr.pop()
    }
}


// 删除某一项数据的公共函数
function removeFromArray(arr,compare){
    const index = arr.findIndex(compare)
    if(index > -1){
        arr.splice(index,1)
    }
}

// 删除所有历史记录的公共函数
function removeAllArray(arr){
    arr.splice(0,arr.length)
}

// 保存历史记录
export function saveSearch(query){
    let searches = storage.get(SEARCH_KEY,[])
    insertArray(searches,query,(item)=>{
        // 这个函数比较的是这个数组中是否有query
        return item == query
    },SEARCH_MAX_LENGTH)

    storage.set(SEARCH_KEY,searches)
    return searches
}

// 从本地缓存读searches
export function loadSearch(){
    return storage.get(SEARCH_KEY,[])
}

// 删除历史记录中的某一项
export function removeSearch(query){
    let searches = storage.get(SEARCH_KEY,[])
    removeFromArray(searches,(item)=>{
        return item === query
    })
    storage.set(SEARCH_KEY,searches)
    return searches
}
// 删除所有的历史记录
export function removeAllSearch(){
    let searches = storage.get(SEARCH_KEY,[])
    removeAllArray(searches)
    storage.set(SEARCH_KEY,searches)
    return searches
}
// 保存播放记录
export function saveplay(song){
    let songs = storage.get(PLAY_KEY,[])
    insertArray(songs,song,(item)=>{
        return item.id == song.id
    },PLAY_MAX_LENGTH)
    storage.set(PLAY_KEY,songs)
    return songs
}
// 从本地缓存中读取songs
export function loadSongs(){
    return storage.get(PLAY_KEY,[])
}


// 保存收藏记录
export function Savefavorite (song){
    let songs = storage.get(FAVORITE_KEY,[])
    insertArray(songs,song,(item)=>{
        return item.id === song.id
    },FAVORITE_MAX_LENGTH)
    storage.set(FAVORITE_KEY,songs)
    return songs
}

// 删除收藏记录
export function Deletefavorite (song){
    let songs = storage.get(FAVORITE_KEY,[])
    removeFromArray(songs,(item)=>{
        return item.id === song.id
    })
    storage.set(FAVORITE_KEY,songs)
    return songs
}

// 从本地缓存中获取收藏记录
export function loadfavorite(){
    return storage.get(FAVORITE_KEY,[])
}
